//
//  File.swift
//  DemoTest
//
//  Created by 韦小新 on 2022/4/20.
//


import Foundation

//每秒向打印台打印一次性能信息，记录打印最后一秒的帧数和预测

class PerformanceReporter {
    //创建一个Bool值可以用来判断是否打印了信息
    static let isEnabled = true
    
    //定义每个报表的index从1开始
    private var reporttIndex = 0
    
    //性能报表中的帧数
    private var frameCount = 0
    
    //真实的操作预测中的帧数
    private var predictionFrameCount = 0
    
    //计时器
    private var repeatingTimer: Timer?
    
    init?() {
        guard PerformanceReporter.isEnabled else { return nil }
        let timer = Timer(timeInterval: 2.0,
                          repeats: true) { [unowned self] _ in
            self.reportToConsole()
        }
        
        //将计时器设置在所有的runloop上都可以用
        RunLoop.current.add(timer, forMode: .common)
        repeatingTimer = timer
    }
    //一段时间后将计时器进行销毁，防止重复释放
    deinit { repeatingTimer?.invalidate() }
    
    //将其添加在帧数计数器中
    func incrementFrameCount() {
        frameCount += 1
    }
    //添加预测帧数
    func inceementPrediction() {
        predictionFrameCount += 1
    }
    //将帧数和预测帧数打印到控制台中
    private func reportToConsole() {
        guard PerformanceReporter.isEnabled else { return }
        reporttIndex += 1
        
        let report = "#\(reporttIndex):" + " \(predictionFrameCount) action predictions" + " across \(frameCount) frames."
        frameCount = 0
        predictionFrameCount = 0
        
        print(report)
    }
    
}
